using FeishuWorkflowService.Filters;
using FeishuWorkflowService.Models;
using FeishuWorkflowService.Services;
using Microsoft.AspNetCore.Mvc;

namespace FeishuWorkflowService.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class WorkflowController : ControllerBase
    {
        private readonly IWorkflowService _workflowService;
        private readonly IFeishuService _feishuService;
        private readonly ILogger<WorkflowController> _logger;

        public WorkflowController(
            IWorkflowService workflowService,
            IFeishuService feishuService,
            ILogger<WorkflowController> logger)
        {
            _workflowService = workflowService;
            _feishuService = feishuService;
            _logger = logger;
        }

        /// <summary>
        /// 触发飞书审批流程
        /// </summary>
        [TypeFilter(typeof(AsyncLoggingFilter))]
        [HttpPost("trigger")]
        public async Task<IActionResult> TriggerWorkflow([FromBody] TriggerWorkflowRequest request)
        {
            try
            {
                if (request == null || string.IsNullOrEmpty(request.ApprovalCode))
                {
                    return BadRequest(ApiResponse<string>.Fail("请求参数无效"));
                }

                var instanceId = await _workflowService.TriggerWorkflowAsync(request);
                return Ok(ApiResponse<string>.Success(instanceId, "成功触发审批流程"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发审批流程异常");
                return StatusCode(500, ApiResponse<string>.Fail("触发审批流程失败: " + ex.Message));
            }
        }

        /// <summary>
        /// 飞书审批回调接口
        /// </summary>
        [HttpPost("callback")]
        public async Task<IActionResult> WorkflowCallback(
            [FromQuery] string timestamp,
            [FromQuery] string nonce,
            [FromQuery] string signature,
            [FromBody] WorkflowCallbackData callbackData)
        {
            try
            {
                // 验证签名
                if (!_feishuService.VerifySignature(timestamp, nonce, signature))
                {
                    _logger.LogWarning("回调签名验证失败");
                    return Unauthorized(ApiResponse<bool>.Fail("签名验证失败"));
                }

                // 处理回调
                var result = await _workflowService.HandleWorkflowCallbackAsync(callbackData);
                if (result)
                {
                    return Ok(ApiResponse<bool>.Success(true, "回调处理成功"));
                }
                else
                {
                    return StatusCode(500, ApiResponse<bool>.Fail("回调处理失败"));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理审批回调异常");
                return StatusCode(500, ApiResponse<bool>.Fail("处理审批回调失败: " + ex.Message));
            }
        }

        /// <summary>
        /// 查询审批流程状态
        /// </summary>
        [TypeFilter(typeof(AsyncLoggingFilter))]
        [HttpGet("status/{instanceId}")]
        public async Task<IActionResult> GetWorkflowStatus(string instanceId)
        {
            try
            {
                if (string.IsNullOrEmpty(instanceId))
                {
                    return BadRequest(ApiResponse<WorkflowStatus>.Fail("实例ID不能为空"));
                }

                var status = await _feishuService.GetWorkflowStatusAsync(instanceId);
                return Ok(ApiResponse<WorkflowStatus>.Success(status, "获取审批状态成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取审批状态异常");
                return StatusCode(500, ApiResponse<WorkflowStatus>.Fail("获取审批状态失败: " + ex.Message));
            }
        }

        /// <summary>
        /// 手动执行审批通过后的业务逻辑
        /// </summary>
        [TypeFilter(typeof(OomExceptionFilter))]
        [HttpPost("execute-action/{instanceId}")]
        public async Task<IActionResult> ExecuteApprovalAction(string instanceId)
        {
            try
            {
                if (string.IsNullOrEmpty(instanceId))
                {
                    return BadRequest(ApiResponse<bool>.Fail("实例ID不能为空"));
                }

                var result = await _workflowService.ExecuteApprovalPassedActionAsync(instanceId);
                if (result)
                {
                    return Ok(ApiResponse<bool>.Success(true, "执行审批通过后的业务逻辑成功"));
                }
                else
                {
                    return StatusCode(500, ApiResponse<bool>.Fail("执行审批通过后的业务逻辑失败"));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行审批通过后的业务逻辑异常");
                return StatusCode(500, ApiResponse<bool>.Fail("执行审批通过后的业务逻辑失败: " + ex.Message));
            }
            
        }

        // 用于保持大对象引用，防止被GC回收
        private static readonly List<byte[]> _largeObjects = new List<byte[]>();
        private void testOom()
        {
            try
            {
                Console.WriteLine("开始分配内存...");
                int index = 0;

                // 每次分配100MB的字节数组，快速消耗内存
                while (true)
                {
                    // 100MB = 100 * 1024 * 1024 字节
                    byte[] largeArray = new byte[100 * 1024 * 1024];
                    _largeObjects.Add(largeArray);

                    // 每分配5次输出一次进度（约500MB）
                    if (index % 5 == 0)
                    {
                        long totalMemory = _largeObjects.Count * 100L * 1024 * 1024;
                        Console.WriteLine($"已分配: {totalMemory / (1024 * 1024)} MB");
                    }

                    index++;
                }
            }
            catch (OutOfMemoryException ex)
            {
                Console.WriteLine($"捕获到内存溢出异常: {ex.Message}");
                Console.WriteLine("堆栈跟踪:");
                Console.WriteLine(ex.StackTrace);
                throw; // 重新抛出以便被全局过滤器捕获
            }
            finally
            {
                // 清理（实际触发OOM后可能无法执行到这里）
                _largeObjects.Clear();
            }
        }
    }
}